<template>
  <el-card>
    <el-card class="search-card">
      <FooterFields
        :footerFields="headerFields"
        :fieldKeys="{
          pusherName: 'operName',
          pushTime: 'createOpeTime',
          pusherDeptName: 'operDeptName',
          pusherAreaName: 'operAreaName',
        }"
      />
    </el-card>
    <el-card class="table-card">
      <el-tabs v-model="tabs.nativeName" @tab-click="handleSwitchTabs">
        <el-tab-pane
          v-for="(item, index) in tabs.tabList"
          :key="item.name + index"
          :label="item.label"
          :name="item.name"
          :disabled="tabs.isDisabled"
        ></el-tab-pane>
      </el-tabs>
      <el-row type="flex" justify="end">
        <el-button type="text" @click="handleGoBack">返回</el-button>
      </el-row>
      <SkusTable
        :loading="tableInfo.loading"
        :data-source="tableInfo.list"
        :columns="tableInfo.columns"
        :showActionCol="isShowActionCol()"
        :actionRender="renderTableBtnAction"
        :showPagination="!isShowActionCol()"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="total"
        :tableRowClassName="setTableRowClassName"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      />
    </el-card>
    <QualificationInfo
      :visible.sync="qualificationInfo.visible"
      :uuid="qualificationInfo.uuid"
    />
  </el-card>
</template>
<script>
import SkusTable from '@/components/skusTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import { commonRequest } from '@/api/commonHttp';
import {
  goodsInfoColumns,
  purchasePriceInfoColumns,
  purchasePriceSteelInfoColumns,
  saleInfoColumns,
  saleSteelInfoColumns,
  acceptStandardInfoColumns,
  qualificationColumns,
  NEW_SALE_TABLE_COLUMNS,
  IMAGE_TEXT_COLUMNS
} from './constants/index';
import QualificationInfo from './QualificationInfo';
import { getTableAction } from '@/utils/getBtnsRender';
import skusPage from '@/mixins/commodity/skusPage';
import { isBeforeRecordDate } from '@/utils/salePrice';

export default {
  mixins: [ skusPage ],
  components: {
    SkusTable,
    FooterFields,
    QualificationInfo
  },
  data () {
    return {
      recordNo: '', // 单据号
      headerFields: {},
      tabs: {
        nativeName: '1', // 当前tab名
        defaultList: [ // 默认tab列集合
          { label: '商品信息', name: '1' },
          { label: '进价信息', name: '2' },
          { label: '进价信息(多计量)', name: '3' },
          { label: '售价信息（新）', name: '9' },
          { label: '售价信息（旧）', name: '4' },
          { label: '售价信息(多计量)', name: '5' },
          { label: '验收标准', name: '6' },
          { label: '资质类型', name: '7' },
          { label: '图文信息', name: '8' }
        ],
        tabList: [], // 当前展示的tab列集合
        defaultTabs: ['1', '6', '7', '8'], // 默认一直展示的tab页签
        isDisabled: false
      },
      tableInfo: {
        list: [],
        columns: [],
        loading: false
      },
      qualificationInfo: { // 资质信息
        visible: false,
        uuid: ''
      },
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 1000 // 当前页码size
      },
      pageSizes: [1000]
    }
  },
  mounted () {
    this.loadInitDataInMounted();
  },
  methods: {
    // 是否展示表格操作栏
    isShowActionCol () {
      return ['7', '8'].includes(this.tabs.nativeName);
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [{ label: '查看', method: this.handleToView }];
      return getTableAction({ h, row, actionList });
    },
    // 在mounted时期加载初始数据
    loadInitDataInMounted () {
      this.recordNo = this.$route.query?.recordNo;
      this.getTabsListByRecordNo();
      this.getHeaderFieldsByRecordNo();
      this.updateTableColumnsByTab();
      this.getTableData();
    },
    // 获取售价表列（旧历史单据-单计量；新售价单据）
    getSalePriceColumns () {
      const isBeforeRecord = isBeforeRecordDate(this.recordNo)
      return isBeforeRecord ? saleInfoColumns : NEW_SALE_TABLE_COLUMNS
    },
    // 更新表列 by tab
    updateTableColumnsByTab () {
      const columnByTab = {
        '1': goodsInfoColumns,
        '2': purchasePriceInfoColumns,
        '3': purchasePriceSteelInfoColumns,
        '4': saleInfoColumns,
        '5': saleSteelInfoColumns,
        '6': acceptStandardInfoColumns,
        '7': qualificationColumns,
        '9': NEW_SALE_TABLE_COLUMNS, // 新售价表列
        '8': IMAGE_TEXT_COLUMNS
      }
      this.tableInfo.columns = columnByTab[this.tabs.nativeName];
    },
    // 获取tab集合
    async getTabsListByRecordNo () {
      const isBeforeRecord = isBeforeRecordDate(this.recordNo)
      const res = await commonRequest({
        url: `/sysback/commit/record/showRecordTab?recordNo=${this.recordNo}`,
        type: 'post'
      });
      if (res?.retData) {
        const showTabList = [...this.tabs.defaultTabs, ...res.retData]
        if (!isBeforeRecord) showTabList.push('9') // 新售价页签
        this.tabs.tabList = this.tabs.defaultList.filter(
          item => showTabList.includes(item.name)
        );
      }
    },
    // 获取表头字段
    async getHeaderFieldsByRecordNo () {
      const res = await commonRequest({
        url: `/sysback/commit/record/getByRecordNo?recordNo=${this.recordNo}`,
        type: 'post'
      });
      if (res?.retData) {
        this.headerFields = res.retData;
      }
    },
    // 获取请求详情api
    getApiByRequestDetails () {
      const { nowPage, pageShow } = this.paginationParams;
      let data = {}
      let url = `/sysback/commit/record/getDetailByRecordNo?recordNo=${this.recordNo}&contentType=${this.tabs.nativeName}&nowPage=${nowPage}&pageShow=${pageShow}`;
      let type = 'post';
      if (this.tabs.nativeName === '7') { // 资质详情
        data = { recordNo: this.recordNo }
        url = '/sysback/commit/record/getQuaPrepareRecordDetail';
        type = 'get';
      }
      if (this.tabs.nativeName == '9') { // 新售价信息
        data = { recordNo: this.recordNo, ...this.paginationParams }
        url = '/sysback/salePrice/secondPhase/prepare/searchRecordForAddSpu'
        type = 'get'
      }
      if (this.tabs.nativeName === '8') { // 图文详情
        url = '/sysback/commit/record/getPrepareSpuListByRecordNo'
        type = 'get'
        data = { recordNo: this.recordNo }
      }
      return { url, type, data }
    },
    // 获取页面详情信息
    async getTableData () {
      const res = await commonRequest({
        ...this.getApiByRequestDetails(),
        loadingFn: state => { this.tableInfo.loading = state; this.tabs.isDisabled = state; }
      })
      if (res?.retData?.results) {
        this.setTableList(res.retData.results);
        this.total = res.retData.totalNum;
      } else if (res?.retData) {
        this.setTableList(res.retData);
      } else {
        this.setTableList([]);
        this.total = 0;
      }
    },
    // 设置表格数据
    setTableList (retData) {
      if (this.tabs.nativeName === '6') {
        this.tableInfo.list = [...this.getTableListByAcceptStandardTab(retData)];
      } else if (['7', '8', '9'].includes(this.tabs.nativeName)) {
        this.tableInfo.list = [...retData];
      } else {
        this.tableInfo.list = this.getTableListByCommonTab(retData);
      }
    },
    // 获取扁平化business1字段
    getFlatBusiness1 (business1) {
      const datasource = JSON.parse(business1);
      if (!datasource || Object.keys(datasource).length === 0) { return {} };
      const layersByVal = {
        'SINGLE': '单层',
        'ONE': '一层',
        'TWO': '两层',
        'Three': '三层'
      }
      return _.omit({
        ...datasource,
        packageLayers: layersByVal[datasource.packageLayers] || '', // 包装层数
        ...datasource?.skuPackageDetailDTO, // 包装信息
      }, ['skuPackageDetailDTO']);
    },
    // 获取通用表格数据
    getTableListByCommonTab (retData) {
      return retData.reduce((value, item) => {
        value.push({
          ...item,
          ...this.getFlatBusiness1(item.business1)
        });
        return value;
      }, []);
    },
    // 获取验收事项表格数据
    getTableListByAcceptStandardTab (retData) {
      return _.cloneDeep(retData).reduce((value, item, index) => {
        const curRow = {
          productName: item.productName,
          brandName: item.brandName,
          categoryName: item.categoryName,
          spuNo: item.spuNo,
          skuNo: item.skuNo,
          checkTime: item.checkTime,
          specDetailStr: item.specDetailStr,
          checkFrequency: item.checkFrequency,
          itemList: item.itemList
        };
        // 新建表头。并准备一行数据的动态列
        // 将行，添加到展示列表
        value.push(this.getCurRowByAcceptStandard(curRow, item.itemList, index));
        return value;
      }, []);
    },
    // 获取验收标准当前row
    getCurRowByAcceptStandard (curRow, itemList, oneIndex) {
      if (!itemList) { return [] }
      const columns = _.cloneDeep(acceptStandardInfoColumns);
      // 获取行内动态列的信息
      const curRows = itemList.reduce((value, item, index) => {
        // 表头，遍历第1行的动态列时，才追加到表头
        if (oneIndex == 0) {
          this.updateTableColumnsByAcceptStandard(columns, item, index);
        }
        // 将行内动态列的信息，平铺到行
        value[`checkCount${index}`] = item.checkCount;
        value[`standardValue${index}`] = item.standardValue;
        value[`upDiffValue${index}`] = item.upDiffValue;
        value[`downDiffValue${index}`] = item.downDiffValue;
        value[`checkMethod${index}`] = item.checkMethod;
        value[`checkItemType${index}`] = item.checkItemType;
        return value;
      }, curRow);
      if (oneIndex == 0) {
        this.tableInfo.columns = columns;
      }
      return curRows;
    },
    // 更新验收标准页签表列
    updateTableColumnsByAcceptStandard (columns, item, index) {
      const hasDiffValueList = [
        { key: 'checkCount', title: '验收次数' },
        { key: 'standardValue', title: '标准值' },
        { key: 'upDiffValue', title: '上差值' },
        { key: 'downDiffValue', title: '下差值' },
        { key: 'checkMethod', title: '验收方法' },
      ];
      const commonList = [
        { key: 'checkCount', title: '验收次数' },
        { key: 'standardValue', title: '标准值' },
        { key: 'checkMethod', title: '验收方法' },
      ]
      if (item.checkItemType !== '2') {
        columns.push(
          this.getExtColumnByAcceptStandard(item, hasDiffValueList, index)
        );
      } else {
        columns.push(
          this.getExtColumnByAcceptStandard(item, commonList, index)
        );
      }
    },
    // 获取验收事项额外扩展表列
    getExtColumnByAcceptStandard (innerEle, list, index) {
      return {
        title: innerEle.checkItemName,
        required: innerEle.isNeed === '1',
        key: innerEle.checkItemUuid,
        width: 150,
        align: 'center',
        children: list.map(item => ({
          title: item.title,
          align: 'center',
          key: `${item.key}${index}`
        })).filter(item => item)
      }
    },
    // 切换tab
    handleSwitchTabs () {
      this.updateTableColumnsByTab();
      this.pagination.pageNum = 1;
      this.getTableData();
    },
    // 查看
    handleToView (row) {
      // 查看资质
      const viewQualification = () => {
        this.qualificationInfo.uuid = row.quaUuid;
        this.qualificationInfo.visible = true;
      }
      // 查看图文
      const viewImageText = () => {
        const { href } = this.$router.resolve({
          name: 'accessSpuRecordImageTextView',
          query: { spuNo: row.spuNo, recordNo: this.recordNo }
        })
        window.open(href, '_blank')
      }
      if (this.tabs.nativeName == '7') return viewQualification()
      if (this.tabs.nativeName == '8') return viewImageText()
    },
    // 返回
    handleGoBack () {
      this.$router.push({ name: 'commodityList' });
    },
    // 获取表格对应spuNo行颜色
    getTableColors () {
      const colors = ['warning-row', 'success-row']
      const spuNos = _.uniq(this.tableInfo.list.map(item => item.spuNo))
      // 只有一个spuNo时，不实现行颜色渲染
      if (spuNos.length == 1) {
        const spuNo = spuNos[0]
        const colorMaps = { [spuNo]: '' }
        return colorMaps
      }
      const colorMaps = spuNos.reduce((value, spuNo, index) => {
        value[spuNo] = index % 2 == 0 ? colors[0] : colors[1]
        return value
      }, {})
      return colorMaps
    },
    // 表格背景色设置
    setTableRowClassName ({ row }) {
      const colorMaps = this.getTableColors() ?? {}
      return colorMaps[row.spuNo] ?? ''
    },
    // 更新图文SPU列表
    async updateImageTextSpuList () {
      const data = {}
      const res = await commonRequest({
        url: '/sysback/commit/record/getPrepareSpuListByRecordNo',
        type: 'get',
        data,
        loadingFn: state => { this.tableInfo.loading = state }
      })
      this.tableInfo.list = res?.retData ?? []
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .el-tabs__header {
  margin: 0;
}
</style>
